package com.easyidea.its.util;

import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.ResourceBundle;
import java.util.Set;

public class PropertyResourceBundle extends ResourceBundle  {

	private Map lookup;
	
	public PropertyResourceBundle(Map<String, String> i18nMap){
		this.lookup = i18nMap;
	}
	
	@Override
	public Enumeration<String> getKeys() {
		 ResourceBundle parent = this.parent;
	        return new ResourceBundleEnumeration(lookup.keySet(),
	                (parent != null) ? parent.getKeys() : null);
	}

	@Override
	protected Object handleGetObject(String key) {
		if (key == null) {
            throw new NullPointerException();
        }
        return lookup.get(key);
	}

}


class ResourceBundleEnumeration implements Enumeration<String> {

    Set<String> set;
    Iterator<String> iterator;
    Enumeration<String> enumeration; // may remain null

    /**
     * Constructs a resource bundle enumeration.
     * @param set an set providing some elements of the enumeration
     * @param enumeration an enumeration providing more elements of the enumeration.
     *        enumeration may be null.
     */
    ResourceBundleEnumeration(Set<String> set, Enumeration<String> enumeration) {
        this.set = set;
        this.iterator = set.iterator();
        this.enumeration = enumeration;
    }

    String next = null;
            
    public boolean hasMoreElements() {
        if (next == null) {
            if (iterator.hasNext()) {
                next = iterator.next();
            } else if (enumeration != null) {
                while (next == null && enumeration.hasMoreElements()) {
                    next = enumeration.nextElement();
                    if (set.contains(next)) {
                        next = null;
                    }
                }
            }
        }
        return next != null;
    }

    public String nextElement() {
        if (hasMoreElements()) {
            String result = next;
            next = null;
            return result;
        } else {
            throw new NoSuchElementException();
        }
    }
}